<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use think\facade\Db;
use think\facade\View;
use think\facade\Filesystem;
use think\exception\ValidateException;
use onekey\File as FileAddons;
use app\admin\BaseController;
use app\admin\model\Catalog as CatalogModel;
use app\admin\model\Config;
use app\admin\model\File as FileModel;
/**
 * 全局方法
 */
class Api extends BaseController
{
    /**
     * 链接查询
     */
    public function link()
    {
        $input = input('post.');
        $data  = [];
        if (! isset($input['table'])){
            foreach (plugin_list() as $key => $value) {
                $data = array_merge($data, $value['route']);
            }
        } else {
            $exist = Db::query("SHOW TABLES LIKE 'mk_".$input['table']."'");
            if (! empty($exist)) {
                $field = Db::query("SHOW COLUMNS FROM mk_".$input['table']."");
                // 模糊查找
                if (! empty($input['keyword'])) {
                    $where[] = [implode('|', array_column($field, 'Field')), 'like', '%'.$input['keyword'].'%'];
                }
                // 状态正常
                if (in_array('status', array_column($field, 'Field'))) {
                    $where[] = ['status', '=', 1];
                }
                $data = Db::name($input['table'])->where($where)->field('id,title,seo_url,catalog_id')->limit(10)->select();
            }
        }
        return json(['status' => 'success', 'message' => '获取成功', 'data' => $data]);
    }

    /**
     * 分类查询
     */
    public function catalog() {
        if ($this->request->isPost()) {
            $input = input('post.');
            $where[] = ['status', '=', 1];
            $where[] = ['theme', '=', theme()];
            if (! empty($input['type'])) {
                $where[] = ['type','=', $input['type']];
            }
            $data  = CatalogModel::where($where)->field('id,pid,title,seo_url,links_type,links_value')->order(['sort'=>'desc'])->select();
            return json(['status' => 'success', 'message' => '获取成功', 'data' => $data]);
        }
    }
    
    /**
     * 检查更新
     */
    public function checkUpdate()
    {
        if ($this->request->isPost()) {
            $data['version'] = config('app.version');
            return json(api_post('tokenSystem/check', $data));
        }
    }
    
    /**
     * 上传文件
     */
    public function upload()
    {
        $file = $this->request->file('file');
        $limitExt = config('upload.ext');
        $limitSize = config('upload.size');
        $type = FileAddons::getType($limitExt, $file->getOriginalName());
        if (empty($type)) return json(['status' => 'error', 'message' => '此类型的文件不支持上传！']);
        try {
            validate([ 'file' => ['fileSize' => $limitSize[$type], 'fileExt' => $limitExt[$type]] ])->check(['file' => $file]);
            $url  = Filesystem::putFile($type, $file);
            $save = FileModel::create([
                'title'       => $file->getOriginalName(),
                'type'        => $type,
                'size'        => $file->getSize(),
                'url'         => '/upload/' . str_replace('\\', '/', $url),
                'status'      => 1,
                'theme'       => theme(),
                'create_time' => date('Y-m-d H:i:s'),
            ]);
            if ($type === "image" && $file->getOriginalExtension() != 'ico' && $file->getOriginalExtension() != 'gif') {
                // 封面图片
                thumbnail($save['url'],100,100);
            }
            // 钩子
            event('UploadEnd', $save);
            return json(['status' => 'success', 'message' => '上传成功', 'data' => $save]);
        } catch (ValidateException $e) {
            return json(['status' => 'error', 'message' => $e->getMessage()]);
        }
    }
}
